home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: in2.uu.net!allegra!alice!bs
- From: bs@research.att.com (Bjarne Stroustrup <9758-26353> 0112760)
- Subject: Re: ? about declaration
- Message-ID: <DM9F2L.4Ht@research.att.com>
- Organization: Info. Sci. Div., AT&T Bell Laboratories, Murray Hill, NJ
- References: <4f2d0r$paq@noc2.drexel.edu>
- Date: Sun, 4 Feb 1996 16:27:57 GMT
-
- st918h5w@dunx1.ocs.drexel.edu (Jonathan Juniman)
-
- > I am confused about something; I have been trying to declare new variables
- > inside of an if statement:
- >
- > aClass::SomeFunction
- > {
- > aClass i();
- >
- > if(SomeCondition == TRUE)
- > {
- > aClass j();
- > }
- > }
- >
- > Some compilers will let me do this, others will not. I was under the
- > impression that C++ always lets you do this, so that you don't have
- > to allocate stack space for j unless SomeCondition is true. Can
- > someone straighten me out about what the standard is, or if there is
- > none at all and this sort of thing is compiler dependent? Please reply by
- > mail.
-
- There are (at least) three separate issues mixed together here:
-
- Can you declared variables in a block within an if statement?
-
- Yes, and this was always the case from the very first C compiler.
-
- Will memory for such variables be allocated only if their branch
- of the if-statement is entered?
-
- This is implementation dependent, the C and C++ standards say
- nothing about that. Allocation of the memmory needed to hold a
- local variable could be done only if its block was entered.
- However, it is more common - and usually much more efficient -
- to allocate local memory for all local variables (whether used
- or unused in a particular call) when the function is called.
-
- Note that a local variable is initialized only if and when a
- thread of execution reaches its definition.
-
- What is the effect of putting empty parentheses after a name being
- declared?
-
- You declare a function. Thus, the example code above doesn't
- declare two variables, it declares two functions. Consider:
-
- void X::f()
- {
- X i; // declare a variable, default initialization
- X j = 0; // declare a variable, initialize to 0
- X k(0); // declare a variable, initialize to 0
- X l(); // declare a function taking no arguments
- }
-
- Thus the () would redundant if you want to declare a variable,
- and leads to a problem.
-
- The reason that ``X l();'' is a function declaration is that's
- what it is (and always was) in C.
-
- - Bjarne
-